<template>
  <div class="appconfigXh height100 bigBgColor">
    <el-container direction="vertical" class="height100  overflowy">
     <div class="partContent" ref="appconMain">
      <div class="part" ref="baseheader">
      <p  class=" smallHeader">{{$t('basic_software_config')}}</p>
      <div ref="headerCon"> <!-- class="height40" -->
        <span v-if="!staticPath">
          <!-- <el-checkbox v-model="systemApps.pmEnable" @change="onSystemAppConfigChange('pm')">启用任务管理软件</el-checkbox>-->
          <el-checkbox v-model="systemApps.qmEnable" @change="onSystemAppConfigChange('qm')">{{$t('qmEnable')}}</el-checkbox> 
          <!-- <el-checkbox v-model="systemApps.amEnable" @change="onSystemAppConfigChange('am')">启用微考勤软件</el-checkbox> -->
          <el-checkbox v-model="systemApps.cmEnable" @change="onSystemAppConfigChange('cm')" size="small">{{$t('cmEnable')}}</el-checkbox>
          <el-checkbox v-model="systemApps.pcmEnable" @change="onSystemAppConfigChange('pcm')" size="small">{{$t('pcmEnable')}}</el-checkbox>
          <el-checkbox v-model="systemApps.kmEnable" @change="onSystemAppConfigChange('km')" size="small">{{$t('kmEnable')}}</el-checkbox>
          <el-checkbox v-model="systemApps.kmTeamEnable" @change="onSystemAppConfigChange('kmTeam')" size="small" v-if="systemApps.kmEnable">{{$t('kmTeamEnable')}}</el-checkbox>
          <el-checkbox v-model="systemApps.kmRealmEnable" @change="onSystemAppConfigChange('kmRealm')" size="small" v-if="systemApps.kmEnable">{{$t('kmRealmEnable')}}</el-checkbox>
          <el-button type="primary" @click="onBindKMRole" size="small" plain class="marginLeft10" v-if="systemApps.kmEnable">{{$t('km_role')}}</el-button>
        </span>
        <span v-else>
          <el-checkbox v-for="item in dynamicSoftware" :label="item.name" v-model="item.enable" :key="item.id" @change="onSystemAppConfigChange(item.id, item.enable)">{{item.description?item.description:item.name}}</el-checkbox>
          <!-- <el-checkbox v-model="KmApps.teamEnable" @change="onSystemAppConfigChange(KmApps.teamId, KmApps.teamEnable)" size="small" v-if="KmApps.enable">{{$t('kmTeamEnable')}}</el-checkbox> -->
          <!-- <el-checkbox v-model="KmApps.realmEnable" @change="onSystemAppConfigChange(KmApps.realmId, KmApps.realmEnable)" size="small" v-if="KmApps.enable">{{$t('kmRealmEnable')}}</el-checkbox> -->
          <el-button type="primary" @click="onBindKMRole" size="small" plain class="marginLeft10" v-if="KmApps.enable">{{$t('km_role')}}</el-button>
        </span>
        
        <kmrolemanager :visible.sync="showKMRoleManagerDlg" v-if="showKMRoleManagerDlg"/>
      </div>
    </div>
    <div class="part searchPart">
      <el-row class="customapp-title" ref="smallHeader">
       <div class=" smallHeader">{{$t('custom_software')}}</div>
      </el-row>
      <el-row ref="smallSearch">
        <search_item :searchItemArr="searchItemArr" @searchItemData="searchItemData">
          <template slot="otherContent">
            <div class="childBtn">
             <button_item btnItemType="primary"  :btnItemLabel="$t('add')"  @onBtnItemClick="onBindCustomApps" />
             <button_item btnItemType="danger"   :btnItemLabel="$t('remove')"  @onBtnItemClick="onUnbindCustomApps" />
            </div>
            </template>
        </search_item>
        </el-row>
      <el-table 
      :data="customApps.datas" 
      @selection-change="onSelectionChange"
      header-cell-class-name="Trpointer tableHeaderbg" 
      stripe 
      size="small"
      class="overflowYScroll">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" :label="$t('software_name')" width="120"></el-table-column>
        <el-table-column :label="$t('mode')" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.type == 0 ? $t('regular_mode') : $t('platform_mode') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" :label="$t('description')" width="200"></el-table-column>
        <el-table-column :label="$t('fettle')" width="100" >
          <template slot-scope="scope">
           <span v-if="scope.row.activated" class="greenColor">{{$t('active')}}</span>
           <span v-else class="redColor">{{$t('inactive')}}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('operating')" width="180" v-if="!($store.state.currentUser && $store.state.currentUser.isOpenSecurity)">
          <template slot-scope="scope">
            <el-button v-if="scope.row.type == 0" @click.stop="rolePermission(scope.row)" type="primary" plain size="small" >{{$t('add_role')}}</el-button>
            <el-button v-if="scope.row.type == 1" @click.stop="onBpmModeConf(scope.row)" type="primary" plain size="small" >{{$t('bpm_Mode_Conf')}}</el-button>
          </template>
        </el-table-column>
        <el-table-column :label="$t('export_operation')" >
          <template slot-scope="scope">
            <el-button @click.stop="exportbasicdataauthority(scope.row)" type="primary" plain size="small" >基础数据</el-button>
            <el-button @click.stop="exportrolemenuauthority(scope.row)" type="primary" plain size="small" >{{$t('role_menu')}}</el-button>
            <el-button @click.stop="exportroleuserauthority(scope.row)" type="primary" plain size="small" >{{$t('role_user')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
    </el-container>
    <dialog_item :dialogTitle="'角色列表'"  :visible.sync="rolePermissionVisible" :isNotShowDefaultBtn="true" dialogClass="paddingTB0Dialog">
      <roleList  :applicationId="applicationId" v-if="rolePermissionVisible"></roleList>
    </dialog_item>
    <appconfig_add :visible.sync="showAddCustomAppDlg" @refresh="initAppConfig" v-if="showAddCustomAppDlg" />
    <bpm_dialog  :visible.sync="showBpmModeDlg" :selectedApp="applicationId" :selectedAppName='selectedAppName' v-if="showBpmModeDlg" />
  </div>
</template>

<script>
import appconfig_add from "@/components/appconfig_add.vue";
import kmrolemanager from "@/components/kmrolemanager.vue";
import roleList from "@/components/roleList.vue";
import search_item from "@/components/common/search_item.vue";
import bpm_dialog from "@/components/bpm_dialog.vue";
import {delMsg} from '../utils/elementui'
export default {
  components: {
    appconfig_add,
    kmrolemanager,
    roleList,
    bpm_dialog,
    search_item
  },
  data() {
    return {
      scrollHeight:null,
      staticPath: this.$api.getStaticPath(),
      systemApps: {},
      KmApps: {},
      checkList: [],
      dynamicSoftware:  [],
      customApps: {},
      showAddCustomAppDlg: false,
      showBpmModeDlg: false,
      showKMRoleManagerDlg: false,
      multipleSelection: [],
      searchdata:{
        currpage: 1,
        pagelines: 10,
        data:{
          name:"",
        }
      },
      rolePermissionVisible:false,
      applicationId:'',
      selectedAppName:'',
      searchItemArr:[],
    };
  },
  created() {
    this.initAppConfig();
    this.searchItemArr=[{type:'input',name:'name',placeholder:this.$t('software_name')}]
  },
  mounted(){
    this.scrollHeight=(document.documentElement.clientHeight || document.body.clientHeight) - 90
  },
  methods: {
    searchItemData(val){
      this.searchdata={
        ...this.searchdata,
        data:{
          ...val
        },
      }
      this.searchTableData()
    },
    /**
     * 导出操作-角色和菜单
     */
   async exportrolemenuauthority(row){
      await delMsg(this.$t('msg_export'), this.$t('msg_tip'),this.$t('msg_confirm'),this.$t('cancel'))
      this.$api.exportrolemenuauthority(row.id);
    },
    async exportbasicdataauthority(row){
      await delMsg(this.$t('msg_export'), this.$t('msg_tip'),this.$t('msg_confirm'),this.$t('cancel'))
      this.$api.exportbasicdataauthority(row.id,this.$route.query.domainid);

    },
    /**
     * 导出操作-角色和用户
     */
   async exportroleuserauthority(row){
      await delMsg(this.$t('msg_export'), this.$t('msg_tip'),this.$t('msg_confirm'),this.$t('cancel'))
      this.$api.exportroleuserauthority(row.id, this.$route.query.domainid);
    },
    resetSearchTableData(){
      this.searchdata.data.name="";
      this.searchdata.currpage = 1;
      this.searchdata.pagelines = 10;
      this.searchTableData();
    },
    onExit(){
      this.rolePermissionVisible=false;
    },
    rolePermission(row){
      this.applicationId=row.id;
      this.rolePermissionVisible=true;
    },
    onBpmModeConf(row){
      this.applicationId=row.id;
      this.selectedAppName=row.name;
      this.showBpmModeDlg = true;
    },
    onBindCustomApps() {
      this.showAddCustomAppDlg = true;
    },
    onBindKMRole(){
      this.showKMRoleManagerDlg = true;
    },
    onSelectionChange(rows) {
      this.multipleSelection = rows;
    },
     initAppConfig() {
      this.$api.getUnbindApps(
        {data:{name: "",}},
        {
          onSucess: resp => {
            if(this.staticPath){
              let response=resp.data.data.datas;
              response.forEach(item=>{
                if(item.type==2){
                  item.enable=false
                  let flag=this.dynamicSoftware.findIndex(e=>e.id==item.id)
                  if(flag==-1){
                    this.dynamicSoftware.push(item)
                  }
                }
              })
                this.dynamicSoftware.map(item => {
                  if(item.id == 'KMAPPID'){
                    this.KmApps = item
                  }
                })
            }else{
              this.systemApps = resp.data.data.datas;
            }
          }
        }
      );
      this.searchTableData();
    },
    onUnbindCustomApps() {
      if(this.multipleSelection.length<=0){
        this.$message({
          showClose: true,
          message: this.$t('msg_select_software'),
          type: "error"
        });
        return false;
      }
      let ids = [];
      
      this.multipleSelection.forEach(row => {
        ids.push(row.id);
      });
      this.removeCustomApps(ids);
      },
    //移除软件
    async removeCustomApps(ids){
      await delMsg(this.$t('msg_confirm_delete'), this.$t('msg_tip'),this.$t('msg_confirm'),this.$t('cancel'))
      this.$api.unbindCustomApps(
        { domainid: this.$route.query.domainid, data: ids },
        {
          onSucess: resp => {
            if (resp.data.errcode == 0) {
              this.$message({
                showClose: true,
                message: this.$t('msg_remove_success'),
                type: "success"
              });
              this.initAppConfig();
            } else {
              this.$message({
                showClose: true,
                message: resp.data.errmsg,
                type: "error"
              });
            }
          }
        }
      );
    
    },
    addCustomApps(ids){
      this.$api.bindCustomApps(
        { domainid: this.$route.query.domainid, data: ids },
        {
          onSucess: resp => {
            if (resp.data.errcode == 0) {
              this.$message({
                showClose: true,
                message: this.$t('msg_add_success'),
                type: "success"
              });
              this.initAppConfig();
            } else {
              this.$message({
                showClose: true,
                message: resp.data.errmsg,
                type: "error"
              });
            }
          }
        }
      );
    },
    searchTableData(){
      this.$api.getCustomAppConfig(
        { domainid: this.$route.query.domainid, data:{...this.searchdata.data}, currpage: this.searchdata.currpage, pagelines: this.searchdata.pagelines  },
        {
          onSucess: resp => {
            let response=resp.data.data,temp=[];
            response.datas.forEach(item=>{
               if(item.type!=2){
                temp.push(item)
               }else{
                let flag=this.dynamicSoftware.findIndex(e=>e.id==item.id)
                if(flag==-1){
                  item.enable=true
                  this.dynamicSoftware.push(item)
                }
                if(item.id == 'KMAPPID'){
                  this.KmApps={
                    ...this.KmApps,
                    enable:true
                  }
                }
               }
            })
            this.customApps=resp.data.data
            this.customApps.datas = temp;
          }
        }
      );
    },
    onSystemAppConfigChange(model, val) {
      let enable = false;
      if(val != undefined){
        enable = val;
      }else{
        switch (model) {
          case "pm":
            enable = this.systemApps.pmEnable;
            break;
          case "qm":
            enable = this.systemApps.qmEnable;
            break;
          case "am":
            enable = this.systemApps.amEnable;
            break;
          case "cm":
            enable = this.systemApps.cmEnable;
            break;
          case "pcm":
            enable = this.systemApps.pcmEnable;
            break;
          case "km":
            enable = this.systemApps.kmEnable;
            if(enable==false){
              this.systemApps.kmTeamEnable=false;
              this.systemApps.kmRealmEnable=false;
            }
            break;
          case "kmTeam":
            enable = this.systemApps.kmTeamEnable;
            break;
          case "kmRealm":
            enable = this.systemApps.kmRealmEnable;
            break;
        }
      }

      if (enable) {
        if(this.staticPath){
          this.addCustomApps([model])
        }else{
          this.$api.enableSystemApplicationConfig(
            { domainid: this.$route.query.domainid, module: model },
            {
              onSucess: resp => {
                if (resp.data.errcode == 0) {
                  this.$message({
                    showClose: true,
                    message: this.$t('msg_save_success'),
                    type: "success"
                  });
                } else {
                  this.$message({
                    showClose: true,
                    message: resp.data.errmsg,
                    type: "error"
                  });
                }
              }
            }
          );
        }
      } else {
        if (this.staticPath) {
          this.removeCustomApps([model])
        } else {
          this.$api.disableSystemApplicationConfig(
            { domainid: this.$route.query.domainid, module: model },
            {
              onSucess: (resp) => {
                if (resp.data.errcode == 0) {
                  this.$message({
                    showClose: true,
                    message: this.$t('msg_save_success'),
                    type: 'success',
                  })
                } else {
                  this.$message({
                    showClose: true,
                    message: resp.data.errmsg,
                    type: 'error',
                  })
                }
              },
            }
          )
        }
      }
    }
  }
};
</script>

<style>
</style>